from nonebot.log import logger
from nonebot import on_command, CommandSession
from nonebot import on_natural_language, NLPSession, IntentCommand
import asyncio
import time
import re

lock = asyncio.Lock()
dialogues = {}

async def record(session: CommandSession):
    pass

@on_natural_language(only_to_me=False)
async def _(session: NLPSession):
    global dialogues
    global lock

    e = session.event
    text = session.msg_text.strip()
    text = re.sub(r'"', '""', text)
    text = re.sub(r'\r', '', text)
    text = re.sub(r'\n', '', text)
    text = re.sub(r'\t', ' ', text)

    t = str(int(round(time.time() * 1000)))

    if len(text) == 0:
        return

    name = ''
    if e.message_type == "group":
        name = 'group' + str(e.group_id)
    else:
        name = 'chat' + str(e.user_id)

    async with lock:
        if not dialogues.__contains__(name):
            dialogues[name] = open("records/" + name + ".csv", "a+", encoding="utf-8")
        f = dialogues[name]
    
    f.write(str(session.event.user_id) + "," + t + ",\"" + text + "\"\n")
    f.flush()

    # return IntentCommand('record', 100.0)